import os
from conanbase import ConanBase
from conan.tools.meson import Meson, MesonToolchain
from conan.tools.env import VirtualBuildEnv
from conan.tools.files import copy

required_conan_version = ">=2.13.0"

class AppConan(ConanBase):
    language = "c++"
    generators = "CMakeDeps", "VirtualBuildEnv", "PkgConfigDeps"

    def package_info(self):
        pass

# 基于meson构建的基类，适用于libmcpp项目
    def layout(self):
        self.folders.source = '.'
        self.folders.build = "build"
        self.cpp.package.libdirs = ["usr/lib64"]

    def generate(self):
        os.environ["PKG_CONFIG"] = "/usr/bin/pkg-config"
        tc = MesonToolchain(self, "ninja")
        ms = VirtualBuildEnv(self)

        tc.extra_ldflags.append("-lstdc++fs")
        tc.extra_cxxflags.append("-Wno-unused-variable")
        tc.extra_cxxflags.append("-Wno-unused-parameter")
        tc.extra_cxxflags.append("-Wno-sign-compare")
        tc.extra_cxxflags.append("-fpermissive")
        tc.extra_cxxflags.append("-Wno-pedantic")
        tc.extra_cxxflags.append("-fno-strict-aliasing")
        tc.extra_cxxflags.append("-Wno-deprecated-copy")
        pkg_path = ms.vars().get("PKG_CONFIG_PATH")
        if pkg_path:
            tc.properties["pkg_config_libdir"] = pkg_path.split(":")

        if self.settings.build_type == "Debug":
            tc.extra_cxxflags.append("-Os")
    
        if self.settings.arch == "armv8" or self.settings.arch == "x86_64":
            tc.project_options["libdir"] = 'usr/lib64'
        else:
            tc.project_options["libdir"] = 'usr/lib'

        if self.options.test:
            tc.project_options["tests"] = True
        else:
            tc.project_options["tests"] = False
        tc.project_options["meson_build"] = False

        tc.project_options["enable_conan_compile"] = True

        tc.generate()

    def build(self):
        meson = Meson(self)
        meson.configure()
        meson.build()

    def package(self):
        meson = Meson(self)
        meson.install()
        if os.path.isfile("permissions.ini"):
            copy(self, "permissions.ini", src=self.source_folder, dst=self.package_folder)
        if os.path.isfile("mds/model.json"):
           copy(self, "model.json", src=os.path.join(self.source_folder, "mds"),
                dst=os.path.join(self.package_folder, "include/mds"))
        if os.path.isfile("mds/service.json"):
           copy(self, "service.json", src=os.path.join(self.source_folder, "mds"),
                dst=os.path.join(self.package_folder, "include/mds"))
        if os.path.isdir("include"):
            copy(self, "*", src=os.path.join(self.source_folder, "include"),
                 dst=os.path.join(self.package_folder, "include"))
        if os.path.isfile("config.json"):
            copy(self, "config.json", src=os.path.join(self.source_folder, "."),
                 dst=os.path.join(self.package_folder, "opt/bmc/apps/devmon"))
        if self.options.test and os.getenv('TRANSTOBIN') is None:
            return
        os.chdir(self.package_folder)
        
        # 对Debug模式编译生成的文件进行strip处理
        if self.settings.build_type == "Debug":
            self._strip_debug_files()
    
    def _strip_debug_files(self):
        """对Debug模式编译生成的文件进行strip处理"""
        import subprocess
        import stat
        
        # 根据架构确定strip工具
        if self.settings.arch == "armv8":
            strip_tool = "aarch64-target-linux-gnu-strip"
        elif self.settings.arch == "x86_64":
            strip_tool = "strip"
        else:
            strip_tool = "strip"
        
        # 查找需要strip的文件
        lib_dirs = []
        if self.settings.arch == "armv8" or self.settings.arch == "x86_64":
            lib_dirs.append("usr/lib64")
        else:
            lib_dirs.append("usr/lib")
        
        # 添加可执行文件和驱动库目录
        bin_dirs = ["opt/bmc/apps/devmon", "opt/bmc/drivers"]
        
        all_dirs = lib_dirs + bin_dirs
        
        for directory in all_dirs:
            dir_path = os.path.join(self.package_folder, directory)
            if not os.path.exists(dir_path):
                continue
                
            for root, dirs, files in os.walk(dir_path):
                for file in files:
                    file_path = os.path.join(root, file)
                    
                    # 检查文件是否为可执行文件或共享库
                    try:
                        if os.path.isfile(file_path) and not os.path.islink(file_path):
                            # 检查文件类型
                            result = subprocess.run(["file", file_path], 
                                                  capture_output=True, text=True, timeout=10)
                            if result.returncode == 0:
                                file_type = result.stdout.lower()
                                if ("executable" in file_type or "current ar archive" in file_type or
                                    "shared object" in file_type or 
                                    "dynamically linked" in file_type):
                                    self.run(f"{strip_tool} -s {file_path}")
                    except Exception as e:
                        print(f"Warning: Error processing {file_path}: {e}")
                        continue